package com.accelstack.cmp.controller;

import com.accelstack.cmp.entity.Rack;
import com.accelstack.cmp.service.RackService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 机架管理控制器
 */
@Tag(name = "机架管理", description = "机架的增删改查接口")
@RestController
@RequestMapping("/api/racks")
@RequiredArgsConstructor
public class RackController {
    
    private final RackService rackService;
    
    @Operation(summary = "创建机架", description = "创建一个新的机架")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "创建成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误")
    })
    @PostMapping
    public ResponseEntity<Rack> create(@Valid @RequestBody Rack rack) {
        Rack created = rackService.create(rack);
        return ResponseEntity.ok(created);
    }
    
    @Operation(summary = "更新机架", description = "更新现有机架的信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "更新成功"),
            @ApiResponse(responseCode = "404", description = "机架不存在")
    })
    @PutMapping("/{id}")
    public ResponseEntity<Rack> update(
            @Parameter(description = "机架ID", required = true) @PathVariable Long id,
            @Valid @RequestBody Rack rack) {
        return rackService.findById(id)
                .map(existing -> {
                    rack.setId(id);
                    Rack updated = rackService.update(rack);
                    return ResponseEntity.ok(updated);
                })
                .orElse(ResponseEntity.notFound().build());
    }
    
    @Operation(summary = "删除机架", description = "根据ID删除机架")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "404", description = "机架不存在")
    })
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(
            @Parameter(description = "机架ID", required = true) @PathVariable Long id) {
        return rackService.findById(id)
                .map(rack -> {
                    rackService.deleteById(id);
                    return ResponseEntity.ok().<Void>build();
                })
                .orElse(ResponseEntity.notFound().build());
    }
    
    @Operation(summary = "查询机架详情", description = "根据ID查询机架的详细信息")
    @GetMapping("/{id}")
    public ResponseEntity<Rack> getById(
            @Parameter(description = "机架ID", required = true) @PathVariable Long id) {
        return rackService.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    @Operation(summary = "查询所有机架", description = "查询系统中所有的机架列表")
    @GetMapping
    public ResponseEntity<List<Rack>> getAll() {
        return ResponseEntity.ok(rackService.findAll());
    }
    
    @Operation(summary = "分页查询机架", description = "分页查询机架列表")
    @GetMapping("/page")
    public ResponseEntity<Page<Rack>> getPage(
            @PageableDefault(size = 20, sort = "id") Pageable pageable) {
        return ResponseEntity.ok(rackService.findAll(pageable));
    }
    
    @Operation(summary = "根据数据中心查询机架", description = "查询指定数据中心下的所有机架")
    @GetMapping("/datacenter/{datacenterId}")
    public ResponseEntity<List<Rack>> getByDatacenterId(
            @Parameter(description = "数据中心ID", required = true) @PathVariable Long datacenterId) {
        List<Rack> racks = rackService.findByDatacenterId(datacenterId);
        return ResponseEntity.ok(racks);
    }
    
    @Operation(summary = "批量创建机架", description = "批量创建多个机架")
    @PostMapping("/batch")
    public ResponseEntity<List<Rack>> batchCreate(@Valid @RequestBody List<Rack> racks) {
        List<Rack> created = rackService.batchCreate(racks);
        return ResponseEntity.ok(created);
    }
    
    @Operation(summary = "批量删除机架", description = "根据ID列表批量删除机架")
    @DeleteMapping("/batch")
    public ResponseEntity<String> batchDelete(@RequestBody List<Long> ids) {
        rackService.batchDelete(ids);
        return ResponseEntity.ok("批量删除成功，共删除 " + ids.size() + " 个机架");
    }
    
    @Operation(summary = "获取机架使用率", description = "获取指定机架的U位使用率")
    @GetMapping("/{id}/utilization")
    public ResponseEntity<?> getUtilization(
            @Parameter(description = "机架ID", required = true) @PathVariable Long id) {
        return rackService.findById(id)
                .map(rack -> ResponseEntity.ok(rackService.getUtilization(id)))
                .orElse(ResponseEntity.notFound().build());
    }
    
    @Operation(summary = "获取机架可用U位", description = "获取指定机架的可用U位列表")
    @GetMapping("/{id}/available-units")
    public ResponseEntity<?> getAvailableUnits(
            @Parameter(description = "机架ID", required = true) @PathVariable Long id) {
        return rackService.findById(id)
                .map(rack -> ResponseEntity.ok(rackService.getAvailableUnits(id)))
                .orElse(ResponseEntity.notFound().build());
    }
    
    @Operation(summary = "获取机架服务器列表", description = "获取指定机架中的所有服务器")
    @GetMapping("/{id}/servers")
    public ResponseEntity<?> getServers(
            @Parameter(description = "机架ID", required = true) @PathVariable Long id) {
        return rackService.findById(id)
                .map(rack -> ResponseEntity.ok(rackService.getServersByRackId(id)))
                .orElse(ResponseEntity.notFound().build());
    }
}

